package com.seraph.zys.web.system;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.seraph.bi.suite.support.security.BaseUser;
import com.seraph.bi.suite.support.security.LoginUtil;
import com.seraph.zys.dao.ScOrgDAO;
import com.seraph.zys.dao.domain.ScOrg;
import com.seraph.zys.exception.ReportLockException;

@Service
@Aspect
public class ReportLockInterceptor {

	private static final String INSERT_METHOD_SIGNATURE = "insert";

	private static final String UPDATE_METHOD_SIGNATURE = "updateByPrimaryKeyForCgs";

	private static final String DELETE_METHOD_SIGNATURE = "deleteByPrimaryKey";

	private ScOrgDAO scOrgDAO;

	@Autowired
	public void setScOrgDAO(ScOrgDAO scOrgDAO) {
		this.scOrgDAO = scOrgDAO;
	}

	@Around("execution(* com.seraph.zys.dao.*.*(..))")
	public Object aroundSayHello(ProceedingJoinPoint pjp)
			throws ReportLockException {
		Object obj = null;
		Signature signature = pjp.getSignature();
		String methodName = signature.toShortString();
		String className = pjp.getTarget().getClass().getSimpleName();

		if (className.startsWith("P") && checkReportLockFlag()) {
			if (checkReportLockFlag(methodName)) {
				throw new ReportLockException("报表已锁定，无法进行更新操作，请与上级部门联系！");
			}
		}
		try {
			obj = pjp.proceed(pjp.getArgs());
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}

	private boolean checkReportLockFlag() {
		BaseUser user = (BaseUser) LoginUtil.getUser();
		String org_Code = user.getOrgCode();
		ScOrg scOrg = scOrgDAO.selectByOrgCode(org_Code);
		if (scOrg != null) {
			int lockflag = scOrg.getReportLockFlag();
			if (lockflag == 1) {
				return true;
			}
		}
		return false;
	}

	private boolean checkReportLockFlag(String methodName) {
		if (INSERT_METHOD_SIGNATURE.equals(methodName)) {
			return true;
		} else if (UPDATE_METHOD_SIGNATURE.equals(methodName)) {
			return true;
		} else if (DELETE_METHOD_SIGNATURE.equals(methodName)) {
			return true;
		}
		return false;
	}

}
